import json
import os

import openpyxl

from config import BASE_PATH, cell_config


class FileUtil:
    # 1.初始化
    def __init__(self, filename):
        # 1.动态获取文件路径
        self.filename = BASE_PATH + os.sep + "data" + os.sep + filename
        print("测试用例路径:", self.filename)
        # 2.打开文件，获取 workbook 对象
        self.workbook = openpyxl.load_workbook(self.filename)
        # 3.获取sheet表单对象
        self.sheet = self.workbook[self.workbook.sheetnames[0]]
        # 4.获取总行数，即总的用例数
        self.row = self.sheet.max_row
        print("总行数为:", self.row)

    # 2.读取 excel
    def read_excel(self):
        # 1.新建空列表，存储所有用例
        cases = list()
        # 2.遍历每行数据
        for i in range(2, self.row + 1):
            # 新建空字典，存储每行数据,case代表一条用例
            case = dict()
            # 读取数据，追加到字典
            try:
                case["method"] = str(self.sheet.cell(i, cell_config.get("method")).value).lower()
                case["path"] = self.sheet.cell(i, cell_config.get("path")).value
                case["headers"] = eval(str(self.sheet.cell(i, cell_config.get("headers")).value))
                case['params'] = eval(str(self.sheet.cell(i, cell_config.get("params")).value))
                case["expect"] = eval(str(self.sheet.cell(i, cell_config.get("expect")).value))
                # dict_data[key]=value, [i, cell_config.get("result")]代表存储实际结果的单元格坐标。 如[2,11]
                case["result"] = [i, cell_config.get("result")]
                # 将字典追加到case列表
                cases.append(case)
                # print("读取的数据为:", cases)
                self.write_json(cases, "case_login.json")
                # 将读取结果写入 excel 中
                self.write_excel([i, cell_config.get("desc")], "读取数据完成！")
            except Exception as e:
                self.write_excel([i, cell_config.get("desc")], e)

    # 3.将测试结果写入 excel
    def write_excel(self, result, msg):
        try:
            # result是列表格式
            self.sheet.cell(result[0], result[1]).value = msg
        except Exception as e:
            self.sheet.cell(result[0], result[1]).value = e
        finally:
            # 保存 excel
            self.workbook.save(self.filename)

    # 4.写入 json
    def write_json(self, case, file_name):
        file_name = BASE_PATH + os.sep + "data" + os.sep + file_name
        with open(file_name, 'w', encoding="utf-8") as f:
            # ensure_ascii=False 不对中文做转义处理，避免中文乱码
            json.dump(case, f, indent=4, ensure_ascii=False)

    # 5.读取json
    def read_json(self, file_name="case_login.json"):
        file_name = BASE_PATH + os.sep + "data" + os.sep + file_name
        with open(file_name, 'r', encoding='utf-8') as f:
            return json.load(f)

# if __name__ == '__main__':
#     FileUtil("case_login.xlsx").read_excel()
#     print(FileUtil("case_login.xlsx").read_json())
#     print(FileUtil("case_login.xlsx").read_json()[1].get("headers").get("Content-Type"))
